/* eslint-disable react/jsx-closing-tag-location,prefer-destructuring */
/**
 * Created by mar105 on 2019-04-03.
 */
import React, { Component } from 'react';
import { Form, Row, Col, Button, Icon, Modal, message } from 'antd';
import moment from 'moment';
import * as commonConfig from '../../utils/config';
import * as commonFunc from './commonFunc';
import * as commonServices from '../../services/services';
import styles from './FastFilter/FastFilter.less';
import * as commonUtils from '../../utils/utils';
import ShowType from './CommonComponent';

const FormItem = Form.Item;

export default class SearchComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {};
    this.sDateFormat = 'YYYY-MM-DD';
  }

  async componentWillMount(sSearchSolutionId) {
    const { token, sModelsId } = this.props;
    const dataUrl = `${commonConfig.server_host}syssearch/getSyssearchData/${sModelsId}?sModelsId=${sModelsId}`; /* 获取快捷查找方案 */
    const dataReturn = (await commonServices.getService(token, dataUrl)).data;
    if (dataReturn.code === 1) {
      const returnData = dataReturn.dataset.rows;
      let addState = {};
      if (!commonUtils.isEmpty(sSearchSolutionId)) { // 保存后重新获取快捷查找，直接默认到最新
        const { masterData } = this.props;
        masterData.sSearchSolutionId = sSearchSolutionId;
        masterData.bCheck = true; // 为了复制到
        addState.masterData = masterData;
        addState.modalVisible = false;
      } else if (commonUtils.isNotEmptyArr(returnData)) { /* 初始化默认查询方案的参数 */
        addState = this.defaultSearchSolution(returnData[0]);
      }
      this.props.onSaveState({ searchSolution: returnData, ...addState });
    } else {
      message.error(dataReturn.msg);
    }
  }

  componentWillReceiveProps(nextProps) {
    const { formData, slaveConfig, bSearchConfig } = nextProps;
    let {
      searchColumns, searchRowKeys, masterData,
    } = nextProps;
    const { sModelsType } = nextProps;
    if (commonUtils.isEmptyArr(searchColumns) && formData.length > 0 && !bSearchConfig) {
      const findFilter = commonFunc.getConfigFieldNameData(slaveConfig, 'bFind');
      searchColumns = [];
      findFilter.forEach((item) => {
        searchColumns.push({ sValue: item.showName, sId: item.sName });
      });
      if (commonUtils.isEmptyArr(searchRowKeys)) { /* 初始化没有默认方案时的 默认查询值 */
        searchRowKeys = [];
        if (commonUtils.isNotEmptyArr(searchColumns)) {
          const key = commonUtils.createSid();
          searchRowKeys.push(key);
          masterData = commonUtils.isEmptyObject(masterData) ? (sModelsType === 'commonClassify' ? { bCheck: false } : { bCheck: true }) : masterData;
          const sFirstValue = searchColumns[0].sId;
          masterData[`sFirst-${key}`] = searchColumns[0].sId;
          const firstDataIndex = commonUtils.isEmpty(sFirstValue) ? 's' : sFirstValue.substring(0, 1) === 't' ? 'p' : sFirstValue.substring(0, 1);
          masterData[`sSecond-${key}`] = commonConfig.seaJudge[firstDataIndex][0].sId;
        }
      }
      this.props.onSaveState({
        searchColumns, searchRowKeys, masterData, bSearchConfig: true,
      });
    }
  }

  defaultSearchSolution(searchSolutionDataRow) {
    const { sModelsType } = this.props;
    const masterData = sModelsType === 'commonClassify' ? { bCheck: false } : { bCheck: true };
    const searchRowKeys = [];
    masterData.sSearchSolutionId = searchSolutionDataRow.sId;
    const filterCondition = JSON.parse(searchSolutionDataRow.sCondition);
    filterCondition.forEach((item) => {
      const key = commonUtils.createSid();
      searchRowKeys.push(key);
      const sFirstValue = item.bFilterName;
      masterData[`sFirst-${key}`] = sFirstValue;
      const sSecondValue = item.bFilterCondition;
      const firstDataIndex = commonUtils.isEmpty(sFirstValue) ? 's' :
        (sSecondValue === 'between' || sSecondValue === 'week' || sSecondValue === 'month') && sFirstValue.substring(0, 1) === 't' ? 'p' : sFirstValue.substring(0, 1);
      masterData[`sSecond-${key}`] = item.bFilterCondition;
      if (sSecondValue === 'day') {
        masterData[`${firstDataIndex}Third-${key}`] = moment().format(this.sDateFormat);
      } else if (sSecondValue === 'month') {
        const dateBetween = [];
        dateBetween.push(moment().startOf('month'));
        dateBetween.push(moment().endOf('month'));
        masterData[`${firstDataIndex}Third-${key}`] = dateBetween;
      } else if (sSecondValue === 'week') {
        const dateBetween = [];
        dateBetween.push(moment().startOf('week'));
        dateBetween.push(moment().endOf('week'));
        masterData[`${firstDataIndex}Third-${key}`] = dateBetween;
      } else if (item.bFilterCondition === 'between') {
        if (item.bFilterValue.split(',').length === 2) {
          const dateBetween = [];
          dateBetween.push(moment(item.bFilterValue.split(',')[0]));
          dateBetween.push(moment(item.bFilterValue.split(',')[1]));
          masterData[`${firstDataIndex}Third-${key}`] = dateBetween;
        }
      } else if (firstDataIndex === 't') {
        masterData[`${firstDataIndex}Third-${key}`] = moment(item.bFilterValue);
      } else {
        masterData[`${firstDataIndex}Third-${key}`] = item.bFilterValue;
      }
    });
    return { masterData, searchRowKeys };
  }
  handeToggle = () => {
    /* 是否展开多出的条件内容 */
    const { expand } = this.props;
    this.props.onSaveState({ expand: !expand });
  };

  handleSearchProps(showConfig) {
    const { masterData } = this.props;
    return {
      form: this.props.form,
      getSqlDropDownData: this.props.getSqlDropDownData,
      handleSqlDropDownNewRecord: this.props.handleSqlDropDownNewRecord,
      getFloatNum: this.props.getFloatNum,
      getDateFormat: this.props.getDateFormat,
      onChange: this.handleMasterChange,
      showConfig,
      formItemLayout: {},
      textArea: false,
      enabled: true,
      dataValue: commonUtils.isNotEmptyObject(masterData) ? masterData[showConfig.sName] : '',
      bTable: false,
    };
  }

  handleSearch = () => {
    const { searchRowKeys, masterData, slaveConfig } = this.props;
    const filterCondition = []; /* 数据筛选条件 */
    searchRowKeys.map((key) => {
      const { [`sFirst-${key}`]: sFirstValue, [`sSecond-${key}`]: sSecondValue } = masterData;
      const firstDataIndex = commonUtils.isEmpty(sFirstValue) ? 's' :
        (sSecondValue === 'between' || sSecondValue === 'week' || sSecondValue === 'month') && sFirstValue.substring(0, 1) === 't' ? 'p' : sFirstValue.substring(0, 1);
      const sThirdName = `${firstDataIndex}Third-${key}`;
      const thirdValue = masterData[sThirdName];
      if (!commonUtils.isEmpty(thirdValue)) {
        if (firstDataIndex === 'p') {
          const tStartDate = moment(thirdValue[0]).format(this.sDateFormat);
          const tEndDate = moment(thirdValue[1]).add(1, 'days').format(this.sDateFormat);
          filterCondition.push({
            bFilterName: sFirstValue,
            bFilterCondition: sSecondValue,
            bFilterValue: `${tStartDate},${tEndDate}`,
          });
        } else if (firstDataIndex === 't') {
          filterCondition.push({
            bFilterName: sFirstValue,
            bFilterCondition: sSecondValue,
            bFilterValue: moment(thirdValue).format(this.sDateFormat),
          });
        } else {
          filterCondition.push({
            bFilterName: sFirstValue,
            bFilterCondition: sSecondValue,
            bFilterValue: thirdValue,
          });
        }
      }
      return true;
    });
    this.props.onGetData(slaveConfig, filterCondition);
  }

  /** 修改主表数据 */
  handleMasterChange = async (name, sFieldName, changeValue, sId, dropDownData) => {
    if (sFieldName === 'sSearchSolutionId') {
      const { searchSolution, slaveConfig } = this.props;
      const iIndex = searchSolution.findIndex(item => item.sId === changeValue[sFieldName]);
      const addState = this.defaultSearchSolution(searchSolution[iIndex]);
      this.props.onSaveState({ ...addState });
      this.props.onGetData(slaveConfig, JSON.parse(searchSolution[iIndex].sCondition));
    } else if (sFieldName.includes('sFirst-')) {
      const { masterData } = this.props.onChange(name, sFieldName, changeValue, sId, dropDownData, true);
      const sFirstValue = masterData[sFieldName];
      const firstDataIndex = commonUtils.isEmpty(sFirstValue) ? 's' : sFirstValue.substring(0, 1);
      const key = sFieldName.substring('sFirst-'.length, sFieldName.length);
      masterData[`sSecond-${key}`] = commonConfig.seaJudge[firstDataIndex][0].sId;
      masterData[`${firstDataIndex}Third-${key}`] = firstDataIndex === 'b' ? false : firstDataIndex === 't' ? moment().format(this.sDateFormat) : '';
      this.props.onSaveState({ masterData });
    } else if (sFieldName.includes('sSecond-')) {
      const { masterData } = this.props.onChange(name, sFieldName, changeValue, sId, dropDownData, true);
      const sSecondValue = masterData[sFieldName];
      const key = sFieldName.substring('sSecond-'.length, sFieldName.length);
      const sFirstValue = masterData[`sFirst-${key}`];
      const firstDataIndex = commonUtils.isEmpty(sFirstValue) ? 's' :
        (sSecondValue === 'between' || sSecondValue === 'week' || sSecondValue === 'month') && sFirstValue.substring(0, 1) === 't' ? 'p' : sFirstValue.substring(0, 1);
      if (sSecondValue === 'day') {
        masterData[`${firstDataIndex}Third-${key}`] = moment().format(this.sDateFormat);
      } else if (sSecondValue === 'month') {
        const dateBetween = [];
        dateBetween.push(moment().startOf('month'));
        dateBetween.push(moment().endOf('month'));
        masterData[`${firstDataIndex}Third-${key}`] = dateBetween;
      } else if (sSecondValue === 'week') {
        const dateBetween = [];
        dateBetween.push(moment().startOf('week'));
        dateBetween.push(moment().endOf('week'));
        masterData[`${firstDataIndex}Third-${key}`] = dateBetween;
      }
      this.props.onSaveState({ masterData });
    } else {
      this.props.onChange(name, sFieldName, changeValue, sId, dropDownData);
    }
  };

  handleFields = (searchColumns) => {
    /* 默认快捷过滤 */
    if (commonUtils.isEmptyArr(searchColumns)) { return; }
    const { masterData, searchRowKeys } = this.props;
    const children = searchRowKeys.map((key) => {
      const { [`sFirst-${key}`]: sFirstValue, [`sSecond-${key}`]: sSecondValue } = masterData;
      const firstDataIndex = commonUtils.isEmpty(sFirstValue) ? 's' :
        (sSecondValue === 'between' || sSecondValue === 'week' || sSecondValue === 'month') && sFirstValue.substring(0, 1) === 't' ? 'p' : sFirstValue.substring(0, 1);
      const showFirstConfig = {
        sId: commonUtils.createSid(),
        sName: `sFirst-${key}`,
        sDropDownType: 'sql',
        iVisCount: 1,
        bNotEmpty: true,
        dropDownData: this.props.searchColumns,
      };
      const showSecondConfig = {
        sId: commonUtils.createSid(),
        sName: `sSecond-${key}`,
        sDropDownType: 'sql',
        bNotEmpty: true,
        iVisCount: 1,
        dropDownData: commonConfig.seaJudge[firstDataIndex],
      };

      const sThirdName = `${firstDataIndex}Third-${key}`;
      const showThirdConfig = {
        sId: commonUtils.createSid(),
        sName: sThirdName,
        sDropDownType: '',
        bNotEmpty: false,
      };
      const showTypeFirstProps = this.handleSearchProps(showFirstConfig);
      const showTypeSecondProps = this.handleSearchProps(showSecondConfig);
      const showTypeThirdProps = this.handleSearchProps(showThirdConfig);
      showTypeThirdProps.enabled = !(sSecondValue === 'day' || sSecondValue === 'week' || sSecondValue === 'month');
      return (
        <Col span={24} key={key} style={{ display: 'block' }}>
          <Col span={8}>
            <ShowType {...showTypeFirstProps} />
          </Col>
          <Col span={8}>
            <ShowType {...showTypeSecondProps} />
          </Col>
          <Col span={8}>
            <ShowType {...showTypeThirdProps} />
            {key > 0 ? (
              <div className={styles.advDelectIcon}>
                <Icon
                  type="minus-circle-o"
                  onClick={() => this.handleRemove(key)}
                />
              </div>
            ) : null}
          </Col>
        </Col>
      );
    });
    return children;
  };

  handleAdd = () => {
    /* 添加条件 */
    const { searchRowKeys, searchColumns, masterData } = this.props;
    const key = commonUtils.createSid();
    searchRowKeys.push(key);
    const sFirstValue = searchColumns[0].sId;
    masterData[`sFirst-${key}`] = searchColumns[0].sId;
    const firstDataIndex = commonUtils.isEmpty(sFirstValue) ? 's' : sFirstValue.substring(0, 1) === 't' ? 'p' : sFirstValue.substring(0, 1);
    masterData[`sSecond-${key}`] = commonConfig.seaJudge[firstDataIndex][0].sId;
    this.props.onSaveState({ searchRowKeys, masterData });
  };

  handleRemove = (key) => {
    /* 移除添加条件 */
    const { searchRowKeys } = this.props;
    if (searchRowKeys.length > 1) {
      const iIndex = searchRowKeys.findIndex(item => item === key);
      searchRowKeys.splice(iIndex, 1);
      this.props.onSaveState({ searchRowKeys });
    }
  };

  handleSave = (e) => {
    /* 保存快捷过滤模板 */
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      /*   验证通过与不通过走不同的流程   */
      if (err) { /*   验证失败   */
        /*   直接渲染显示错误提示   */
        for (const sFieldName of Object.keys(err)) {
          const key = sFieldName.substring('Third-'.length + 1, sFieldName.length);
          const sFirstValue = values[`sFirst-${key}`];
          const iIndex = this.props.searchColumns.findIndex(item => item.sId === sFirstValue);
          const showName = iIndex > -1 ? this.props.searchColumns[iIndex].sValue : '';
          message.error(err[sFieldName].errors[0].message.replace('undefined', showName));
        }
      } else { /*   验证成功   */
        this.props.onSaveState({
          modalVisible: true,
        });
      }
    });
  };

  handleOk = (e) => {
    e.preventDefault();
    this.props.form.validateFields(async (err) => {
      /*   验证通过与不通过走不同的流程   */
      if (err) { /*   验证失败   */
        /*   直接渲染显示错误提示   */
        for (const sFieldName of Object.keys(err)) {
          message.error(err[sFieldName].errors[0].message);
        }
      } else { /*   验证成功   */
        const { sModelsId, masterData, searchRowKeys } = this.props;
        const dataUrl = `${commonConfig.server_host}syssearch/addSyssearch?sModelsId=${sModelsId}`;
        const filterCondition = [];
        searchRowKeys.map((key) => {
          const { [`sFirst-${key}`]: sFirstValue, [`sSecond-${key}`]: sSecondValue } = masterData;
          const firstDataIndex = commonUtils.isEmpty(sFirstValue) ? 's' :
            (sSecondValue === 'between' || sSecondValue === 'week' || sSecondValue === 'month') && sFirstValue.substring(0, 1) === 't' ? 'p' : sFirstValue.substring(0, 1);
          const sThirdName = `${firstDataIndex}Third-${key}`;
          const thirdValue = masterData[sThirdName];
          if (thirdValue !== undefined) {
            if (firstDataIndex === 'p') {
              const tStartDate = moment(thirdValue[0]).format(this.sDateFormat);
              const tEndDate = moment(thirdValue[1]).add(1, 'days').format(this.sDateFormat);
              filterCondition.push({
                bFilterName: sFirstValue,
                bFilterCondition: sSecondValue,
                bFilterValue: `${tStartDate},${tEndDate}`,
              });
            } else if (firstDataIndex === 't') {
              filterCondition.push({
                bFilterName: sFirstValue,
                bFilterCondition: sSecondValue,
                bFilterValue: moment(thirdValue).format(this.sDateFormat),
              });
            } else {
              filterCondition.push({
                bFilterName: sFirstValue,
                bFilterCondition: sSecondValue,
                bFilterValue: thirdValue,
              });
            }
          }
          return true;
        });
        const value = {
          sFormId: sModelsId,
          sCondition: filterCondition,
          sName: masterData.sSolutionName,
        };
        const dataReturn = (await commonServices.postValueService(this.props.app.token, value, dataUrl)).data;
        if (dataReturn.code === 1) {
          const returnData = dataReturn.dataset.rows;
          message.success(dataReturn.msg);
          await this.componentWillMount(returnData[0].sId);
        } else {
          message.error(dataReturn.msg);
        }
      }
    });
  };

  handleDel = async (e) => {
    /* 删除快捷过滤模板 */
    e.preventDefault(); /* 防止动画删除 */
    const { slaveConfig, masterData, sModelsId } = this.props;
    if (commonUtils.isNotEmptyObject(masterData) && !commonUtils.isEmpty(masterData.sSearchSolutionId)) {
      const dataUrl = `${commonConfig.server_host}syssearch/deleteSyssearch/${sModelsId}/${masterData.sSearchSolutionId}?sModelsId=${sModelsId}`;
      const dataReturn = (await commonServices.getService(this.props.app.token, dataUrl)).data;
      if (dataReturn.code === 1) {
        message.success(dataReturn.msg);
        await this.componentWillMount();
        const { searchSolution } = this.props;
        if (commonUtils.isNotEmptyArr(searchSolution)) {
          this.props.onGetData(slaveConfig, JSON.parse(searchSolution[0].sCondition));
        }
      } else {
        message.error(dataReturn.msg);
      }
    }
  };

  handleReset = () => {
    /* 清空搜索条件 */
    const { searchColumns, masterData: masterDataOld, sModelsType } = this.props;
    const searchRowKeys = [];
    const key = commonUtils.createSid();
    const masterData = sModelsType === 'commonClassify' ? { bCheck: false } : { bCheck: true };
    masterData.sSearchSolutionId = masterDataOld.sSearchSolutionId;
    searchRowKeys.push(key);
    const sFirstValue = searchColumns[0].sId;
    masterData[`sFirst-${key}`] = searchColumns[0].sId;
    const firstDataIndex = commonUtils.isEmpty(sFirstValue) ? 's' : sFirstValue.substring(0, 1) === 't' ? 'p' : sFirstValue.substring(0, 1);
    masterData[`sSecond-${key}`] = commonConfig.seaJudge[firstDataIndex][0].sId;
    this.props.onSaveState({ searchRowKeys, masterData });
  };

  handleCancel = () => {
    /* 关闭弹窗 */
    this.props.onSaveState({ modalVisible: false });
  };

  render() {
    const {
      searchSolution, searchColumns, expand, activeTagId, sType, modalVisible, confirmLoading, masterData,
    } = this.props;
    /* 过滤另存方案界面显示 */
    const showSearchSolutionConfig = {
      sId: commonUtils.createSid(),
      sName: 'sSearchSolutionId',
      sDropDownType: 'sql',
      iVisCount: 1,
      sVisColumnName: 'sName',
      dropDownData: searchSolution,
    };
    const showTypeSearchSolutionProps = this.handleSearchProps(showSearchSolutionConfig);
    showTypeSearchSolutionProps.formItemLayout = { style: { width: '14%', padding: '11px 0 0px 5px' } };
    const showSolutionNameConfig = {
      sId: commonUtils.createSid(),
      sName: 'sSolutionName',
      sDropDownType: '',
      bNotEmpty: modalVisible,
      showName: '方案名称',
    };
    let bBtnDelDisabled = false;
    if (commonUtils.isNotEmptyArr(searchSolution) && commonUtils.isNotEmptyObject(masterData)) {
      const iIndex = searchSolution.findIndex(item => item.sId === masterData.sSearchSolutionId);
      if (iIndex > -1) {
        bBtnDelDisabled = this.props.app.userinfo.sType !== 'sysadmin' && searchSolution[iIndex].sType === 'common';
      }
    }
    const showTypeSolutionNameProps = this.handleSearchProps(showSolutionNameConfig);
    return (<div> {commonUtils.isEmptyArr(searchColumns) ? '' : <div className={styles.fastFilter}>
      <Col span={24}>
        <ShowType {...showTypeSearchSolutionProps} placeholder="请选择方案" />
      </Col>
      <Row className={expand ? styles.advRowActive : styles.advRow}>
        {this.handleFields(searchColumns)}
        <Button type="primary" className={styles.advTogIcon} onClick={this.handeToggle} icon={expand ? 'up' : 'down'} />
        {
          (activeTagId === 'default' || (sType === 'common' && this.props.app.userinfo.sType !== 'sysadmin')) ?
            <Col span={24} style={{ display: expand ? 'block' : 'none' }}>
              <Col span={20}>
                <div className={styles.advButton}>
                  <Button
                    type="primary"
                    onClick={this.handleAdd}
                  >
                    <Icon type="plus" /> 添加条件
                  </Button>
                </div>
              </Col>
              <Col span={4}>
                <div className={styles.advButton}>
                  <Button onClick={this.handleSave}>
                    保存
                  </Button>
                </div>
              </Col>
            </Col>
            :
            <Col span={24} style={{ display: expand ? 'block' : 'none' }}>
              <Col span={16}>
                <div className={styles.advButton}>
                  <Button
                    type="primary"
                    onClick={this.handleAdd}
                  >
                    <Icon type="plus" /> 添加条件
                  </Button>
                </div>
              </Col>
              <Col span={4}>
                <div className={styles.advButton}>
                  <Button onClick={this.handleSave}>
                    保存
                  </Button>
                </div>
              </Col>
              <Col span={4}>
                <div className={styles.advButton}>
                  <Button onClick={this.handleDel} disabled={bBtnDelDisabled}>
                    删除
                  </Button>
                </div>
              </Col>
            </Col>
        }
      </Row>
      <Col span={24} className={styles.advCol}>
        <Button type="primary" onClick={this.handleSearch}>搜索</Button>
        <Button type="primary" style={{ marginLeft: 8 }} onClick={this.handleReset}>
          清空
        </Button>
      </Col>
      <Modal visible={modalVisible} title="过滤方案另存" onOk={this.handleOk} onCancel={this.handleCancel} okText="确认" cancelText="取消" confirmLoading={confirmLoading} maskClosable={false}>
        <FormItem>
          <ShowType {...showTypeSolutionNameProps} />
        </FormItem>
      </Modal>
    </div>}</div>);
  }
}
